package com.xmlt.ui.builder;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.w3c.dom.Document;

import com.xmlt.core.template.resolver.IDefaultTemplateDescriptor;
import com.xmlt.core.template.resolver.IResolver;

public class ProjectResolver implements IResolver {
	protected IProject project;
	protected DocumentBuilder documentBuilder;

	public ProjectResolver(IProject prj) {
		project = prj;
		DocumentBuilderFactory domFactory = DocumentBuilderFactory
				.newInstance();
		try {
			documentBuilder = domFactory.newDocumentBuilder();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Document find(String ref) {
//		if (!ref.startsWith("/"))
//			ref = "/" + ref;
		IFile file = project.getFile(ref);
		if (file.exists()) {
			try {
				file.refreshLocal(IFile.DEPTH_INFINITE, null);
				return documentBuilder.parse(file.getContents());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public void save(Document doc, String ref, boolean overwrite) {
		if (!ref.startsWith("/"))
			ref = "/" + ref;
		try {
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			IFile file = project.getFile(ref);
			StringWriter sw = new StringWriter();
			xformer.transform(new DOMSource(doc), new StreamResult(sw));
			ByteArrayInputStream bis = new ByteArrayInputStream(sw.toString().getBytes());
			if (file.exists()) {
				file.setContents(bis, true, true, null);
			} else {
				file.create(bis, true, null);
			}
			file.refreshLocal(IFile.DEPTH_INFINITE, null);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<IDefaultTemplateDescriptor> getDefaultTemplateDescriptors() {
		return new ArrayList<IDefaultTemplateDescriptor>();
	}

}
